package com.ll.gulimall.test.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/info")
    @ResponseBody
    public String info(@RequestParam("token") String token) {
        return stringRedisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(name = "sso_token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            //用户之前在别的系统登录过 留下了token 则不需要登录该系统
            return "redirect:" + url + "?token=" + token;
        }
        model.addAttribute("redirect_url", url);
        return "login";
    }


    @PostMapping("/doLogin")
    public String doLoing(String redirect_url, String username, String password, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录Yes 将登录成功的用户存起来
            String token = UUID.randomUUID().toString().replace("_", "");
            //存用户
            stringRedisTemplate.opsForValue().set(token, username);
            //给浏览器发送cookie信息 实现sso登录
            Cookie cookie = new Cookie("sso_token", token);
            response.addCookie(cookie);
            return "redirect:" + redirect_url + "?token=" + token;
        }
        //登录失败
        return "login";
    }
}
